package com.iris.live.services.services.impl;

import com.google.common.collect.Maps;
import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.common.LshMsgUtils;
import com.iris.live.services.common.StringUtils;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.data.repositories.impl.ImgtRepositoryImpl;
import com.iris.live.services.services.ApprovalService;
import com.iris.live.services.services.TimedTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ThinkPad on 2016/11/3.
 */
@Service
public class TimedTaskServiceImpl implements TimedTaskService {
    private static Logger logger = LoggerFactory.getLogger(TimedTaskServiceImpl.class);

    @Autowired
    private TimedTaskRepository timedTaskRepository;

    @Autowired
    private WeekReprotRepository weekReprotRepository;

    @Autowired
    private TWeeklySm2RosRptRepository tWeeklySm2RosRptRepository;

    @Autowired
    private FlowupReportRepository flowupReportRepository;

    @Autowired
    private ApprovalService approvalService;

    @Autowired
    private MessageSettingRepository messageSettingRepository;

    @Autowired
    private 用户Repository repository用户;

    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;

    @Autowired
    private ImgtRepositoryImpl imgtRepositoryImpl;

    @Autowired
    private TMonthlySaleRptRepository tMonthlySaleRptRepository;

    @Autowired
    private Lsh金融服务费Repository lsh金融服务费Repository;

    @Autowired
    private  ReportRepository   reportRepository;

    @Autowired
    private 线索统计Repository 线索统计Repository;

    @Override
    @Transactional
    public void getSendMsgListTask() {
        List list开票提醒 = timedTaskRepository.getSendMsgListTask开票提醒();
        for (int i = 0; i < list开票提醒.size(); i++) {
            Map m = (Map) list开票提醒.get(i);
            MessageSettingModel msgSet调出财务 = messageSettingRepository.findByPermitAndType((String) m.get("调出经销商"), "4", "1");
            if (msgSet调出财务 == null) {
                logger.error("经销商" + (String) m.get("调出经销商") + "没有设置调出经销商的财务专员！");
            }
            if (msgSet调出财务 != null) {
                用户Model m财务 = repository用户.findByPermitAndUserName(msgSet调出财务.getPermit(), "财务专员", msgSet调出财务.getUser());
                if (m财务 != null) {
                    String latestDate = null;
                    if (m.get("expectedLateMoneyInAccount") == null) {
                        latestDate = "";
                    } else {
                        latestDate = getFormatDate((Date) m.get("expectedLateMoneyInAccount"));
                    }
                    String name = lsh经销商表Repository.findNameByPermit((String) m.get("调出经销商"));
                    String content调入财务 = "贵公司于 " + getFormatDate((Date) m.get("out_confirm_date")) + "确认自" +
                            name + "经销商调入生产号为" + m.get("生产号") + "的车辆,最晚款项到账日期为" + latestDate +
                            "请尽快开具调车增票";
                    LshMsgUtils.getLshMsg((String) m.get("调出经销商"), "LiVE系统", m财务.get许可(), m财务.get用户名(), "调车调入", content调入财务, "LiVE系统", (String) m.get("a.customTel"));
                }
            }
        }

        List list付款提醒 = timedTaskRepository.getSendMsgListTask付款提醒();
        for (int j = 0; j < list付款提醒.size(); j++) {
            Map m = (Map) list付款提醒.get(j);
            //调入方财务消息：xx经销商（调出方）于xx月xx日已经开具xx生产号车辆的调车增票，请于xx年xx月xx日（最晚款项到账日期）前完成付款。
            MessageSettingModel msgSet调入财务 = messageSettingRepository.findByPermitAndType((String) m.get("调入经销商"), "2", "1");
            if (msgSet调入财务 == null) {
                logger.error("经销商" + (String) m.get("调入经销商") + "没有设置调入经销商的财务专员！");
            }
            if (msgSet调入财务 != null) {
                用户Model m财务 = repository用户.findByPermitAndUserName(msgSet调入财务.getPermit(), "财务专员", msgSet调入财务.getUser());
                if (m财务 != null) {
                    String latestDate = null;
                    if (m.get("expectedLateMoneyInAccount") == null) {
                        latestDate = "";
                    } else {
                        latestDate = getFormatDate((Date) m.get("expectedLateMoneyInAccount"));
                    }
                    String name = lsh经销商表Repository.findNameByPermit((String) m.get("调出经销商"));
                    String content调入财务 = name + "经销商于" + getFormatDate((Date) m.get("invoice_issuing_date")) + "已经开具生产号为" + m.get("生产号") + "的调车增票，" +
                            "请于" + latestDate + "前完成付款。";
                    LshMsgUtils.getLshMsg((String) m.get("调出经销商"), "LiVE系统", m财务.get许可(), m财务.get用户名(), "调车调入", content调入财务, "LiVE系统", (String) m.get("a.customTel"));
                }
            }
        }
        List list收款提醒 = timedTaskRepository.getSendMsgListTask收款提醒();
        for (int k = 0; k < list收款提醒.size(); k++) {
            Map m = (Map) list收款提醒.get(k);
            //xx经销商（调入方）已经于xx年xx月xx日完成付款，请查询是否到账并确认已经收款
            MessageSettingModel msgSet调出财务 = messageSettingRepository.findByPermitAndType((String) m.get("调出经销商"), "4", "1");
            if (msgSet调出财务 == null) {
                logger.error("经销商" + (String) m.get("调出经销商") + "没有设置调出经销商的财务专员！");
            }
            if (msgSet调出财务 != null) {
                用户Model m财务 = repository用户.findByPermitAndUserName(msgSet调出财务.getPermit(), "财务专员", msgSet调出财务.getUser());
                if (m财务 != null) {
                    String name = lsh经销商表Repository.findNameByPermit((String) m.get("调入经销商"));
                    String content = name + "已经于" +
                            getFormatDate((Date) m.get("fund_out_date"))
                            + "完成付款,请查询是否到账并确认已经收款";
                    LshMsgUtils.getLshMsg((String) m.get("调入经销商"), "LiVE系统", m财务.get许可(), m财务.get用户名(), "调车调入", content, "LiVE系统", (String) m.get("a.customTel"));
                }
            }
        }
    }

    @Override
    @Transactional
    public void getStatisticsFormDataStorage(Integer year, String month) {
        if (year == null || month == null) {
            //获取当前日期前一天的年份和月份
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new java.util.Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            java.util.Date date = calendar.getTime();
            year = Integer.valueOf(new SimpleDateFormat("yyyy").format(date));
            month = new SimpleDateFormat("MM").format(date);
        }
        //获取所有的经销商许可
        List<Lsh经销商表Model> modelList = lsh经销商表Repository.findAllPermit();
        for (int i = 0; i < modelList.size(); i++) {
            Lsh经销商表Model model = modelList.get(i);
            String permit = model.getBmbs();

            //获取本许可本年本月的所有指标
          //  Map map = imgtRepositoryImpl.statisticsFormExportByPermit(permit, year, month);
            Map map =new HashMap();

                    //新增或更新MB的数据
            TMonthlySaleRptModel tMB = tMonthlySaleRptRepository.findByPermitAndYearAndMonthAndBrand(permit, year, month, "MB");
            if (tMB == null) {
                tMB = new TMonthlySaleRptModel();
                tMB.setPermit(permit);
                tMB.setStatMonth(month);
                tMB.setStatYear(year);
                tMB.setModel("MB");//品牌
            }
            Double a1 = Double.parseDouble(((List) map.get("Volume_MB_零售签署目标")).get(0).toString());
            tMB.setSignedRetailTa(a1);//零售签署目标（台次）
            Double a2 = (Double.parseDouble(((List) map.get("Volume_MB_实际零售NBI")).get(0).toString()));
            tMB.setActualRetailNbi(a2);//实际零售NBI（台次）
            Double a3 = (Double.parseDouble(((List) map.get("Volume_MB_ROS零售目标")).get(0).toString()));
            tMB.setRosRetailTa(a3);//ROS零售目标（台次）
            Double a4 = (Double.parseDouble(((List) map.get("Volume_MB_实际零售NBI")).get(0).toString()));
            tMB.setActualRetailRos(a4);//实际零售ROS（台次）

            Double a5 = (Double.parseDouble(((List) map.get("ClosingStock_MB_90天以下库存台数")).get(0).toString()));
            tMB.setLt89DaysStock(a5);//90天以下库存台数
            Double a6 = (Double.parseDouble(((List) map.get("ClosingStock_MB_90-149天库存台数")).get(0).toString()));
            tMB.setDaysStock90149(a6);//90-149天库存台数
            Double a7 = (Double.parseDouble(((List) map.get("ClosingStock_MB_大于150天库存台数")).get(0).toString()));
            tMB.setGet150DaysStock(a7);//大于150天库存台数

            Double a8 = (Double.parseDouble(((List) map.get("Finance_MB_新车外部销售收入")).get(0).toString()));
            tMB.setNewCarExternalSalesRevenue(a8);//新车外部销售收入
            Double a9 = (Double.parseDouble(((List) map.get("Finance_MB_GP1金额")).get(0).toString()));
            tMB.setActualGpi(a9);//GP1
            Double a10 = (Double.parseDouble(((List) map.get("Finance_MB_GP2金额")).get(0).toString()));
            tMB.setActualGpii(a10);//GP2
            Double a11 = (Double.parseDouble(((List) map.get("Finance_MB_SI金额")).get(0).toString()));
            tMB.setActualSi(a11);//SI

            Double a12 = (Double.parseDouble(((List) map.get("OtherIncome_MB_二手车评估台数")).get(0).toString()));
            tMB.setUsedCarAppraisalVolume(a12);//二手车评估台数
            Double a13 = (Double.parseDouble(((List) map.get("OtherIncome_MB_二手车置换台数")).get(0).toString()));
            tMB.setUsedCarTradeInVolume(a13);//二手车置换台数
            Double a14 = (Double.parseDouble(((List) map.get("OtherIncome_MB_置换手续费收入")).get(0).toString()));
            tMB.setTradeInCommission(a14);//置换手续费收入
            Double a15 = (Double.parseDouble(((List) map.get("OtherIncome_MB_后市场产品营业额")).get(0).toString()));
            tMB.setAfterMarketProductRevenue(a15);//后市场产品营业额
            Double a16 = (Double.parseDouble(((List) map.get("OtherIncome_MB_后市场产品销售毛利")).get(0).toString()));
            tMB.setAfterMarketProductGp(a16);//后市场产品销售毛利
            Double a17 = (Double.parseDouble(((List) map.get("OtherIncome_MB_新保台数")).get(0).toString()));
            tMB.setNewCarInsurance(a17);//新保台数
            Double a18 = (Double.parseDouble(((List) map.get("OtherIncome_MB_新保手续费收入")).get(0).toString()));
            tMB.setNewCarInsuranceCommission(a18);//新保手续费收入
            Double a19 = (Double.parseDouble(((List) map.get("OtherIncome_MB_金融零售数")).get(0).toString()));
            tMB.setNewCarFinancing(a19);//金融零售数
            Double a20 = (Double.parseDouble(((List) map.get("OtherIncome_MB_新车Agility台数")).get(0).toString()));
            tMB.setNewCarAgility(a20);//新车Agility台数
            Double a21 = (Double.parseDouble(((List) map.get("OtherIncome_MB_金融手续费收入")).get(0).toString()));
            tMB.setFinancingCommission(a21);//金融手续费收入
            Double a22 = (Double.parseDouble(((List) map.get("OtherIncome_MB_金融服务费收入")).get(0).toString()));
            tMB.setFinancingServiceFeeMargin(a22);//金融服务费收入
            Double a23 = (Double.parseDouble(((List) map.get("OtherIncome_MB_上牌服务费收入")).get(0).toString()));
            tMB.setRegistrationServiceFeeMargin(a23);//上牌服务费收入
            Double a24 = (Double.parseDouble(((List) map.get("OtherIncome_MB_其他服务费收入")).get(0).toString()));
            tMB.setOtherServiceFeeMargin(a24);//其他服务费收入
            tMonthlySaleRptRepository.save(tMB);


            //新增或更新MM的数据
            TMonthlySaleRptModel tMM = tMonthlySaleRptRepository.findByPermitAndYearAndMonthAndBrand(permit, year, month, "MM");
            if (tMM == null) {
                tMM = new TMonthlySaleRptModel();
                tMM.setPermit(permit);
                tMM.setStatMonth(month);
                tMM.setStatYear(year);
                tMM.setModel("MM");//品牌
            }
            Double b1 = (Double.parseDouble(((List) map.get("Volume_MM_销售业务指导")).get(0).toString()));
            tMM.setSalesGuideline(b1);//销售业务指导
            Double b2 = (Double.parseDouble(((List) map.get("Volume_MM_实际零售NBI")).get(0).toString()));
            tMM.setActualRetailNbi(b2);//实际零售NBI
            Double b3 = (Double.parseDouble(((List) map.get("Volume_MM_ROS零售目标")).get(0).toString()));
            tMM.setRosRetailTa(b3);//ROS零售目标（台次）
            Double b4 = (Double.parseDouble(((List) map.get("Volume_MM_实际零售NBI")).get(0).toString()));
            tMM.setActualRetailRos(b4);//实际零售ROS（台次）

            Double b5 = (Double.parseDouble(((List) map.get("ClosingStock_MM_90天以下库存台数")).get(0).toString()));
            tMM.setLt89DaysStock(b5);//90天以下库存台数
            Double b6 = (Double.parseDouble(((List) map.get("ClosingStock_MM_90-149天库存台数")).get(0).toString()));
            tMM.setDaysStock90149(b6);//90-149天库存台数
            Double b7 = (Double.parseDouble(((List) map.get("ClosingStock_MM_大于150天库存台数")).get(0).toString()));
            tMM.setGet150DaysStock(b7);//大于150天库存台数

            Double b8 = (Double.parseDouble(((List) map.get("Finance_MM_新车外部销售收入")).get(0).toString()));
            tMM.setNewCarExternalSalesRevenue(b8);//新车外部销售收入
            Double b9 = (Double.parseDouble(((List) map.get("Finance_MM_GP1金额")).get(0).toString()));
            tMM.setActualGpi(b9);//GP1
            Double b10 = (Double.parseDouble(((List) map.get("Finance_MM_GP2金额")).get(0).toString()));
            tMM.setActualGpii(b10);//GP2
            Double b11 = (Double.parseDouble(((List) map.get("Finance_MM_SI金额")).get(0).toString()));
            tMM.setActualSi(b11);//SI

            Double b12 = (Double.parseDouble(((List) map.get("OtherIncome_MM_二手车评估台数")).get(0).toString()));
            tMM.setUsedCarAppraisalVolume(b12);//二手车评估台数
            Double b13 = (Double.parseDouble(((List) map.get("OtherIncome_MM_二手车置换台数")).get(0).toString()));
            tMM.setUsedCarTradeInVolume(b13);//二手车置换台数
            Double b14 = (Double.parseDouble(((List) map.get("OtherIncome_MM_置换手续费收入")).get(0).toString()));
            tMM.setTradeInCommission(b14);//置换手续费收入
            Double b15 = (Double.parseDouble(((List) map.get("OtherIncome_MM_后市场产品营业额")).get(0).toString()));
            tMM.setAfterMarketProductRevenue(b15);//后市场产品营业额
            Double b16 = (Double.parseDouble(((List) map.get("OtherIncome_MM_后市场产品销售毛利")).get(0).toString()));
            tMM.setAfterMarketProductGp(b16);//后市场产品销售毛利
            Double b17 = (Double.parseDouble(((List) map.get("OtherIncome_MM_新保台数")).get(0).toString()));
            tMM.setNewCarInsurance(b17);//新保台数
            Double b18 = (Double.parseDouble(((List) map.get("OtherIncome_MM_新保手续费收入")).get(0).toString()));
            tMM.setNewCarInsuranceCommission(b18);//新保手续费收入
            Double b19 = (Double.parseDouble(((List) map.get("OtherIncome_MM_金融零售数")).get(0).toString()));
            tMM.setNewCarFinancing(b19);//金融零售数
            Double b20 = (Double.parseDouble(((List) map.get("OtherIncome_MM_新车Agility台数")).get(0).toString()));
            tMM.setNewCarAgility(b20);//新车Agility台数
            Double b21 = (Double.parseDouble(((List) map.get("OtherIncome_MM_金融手续费收入")).get(0).toString()));
            tMM.setFinancingCommission(b21);//金融手续费收入
            Double b22 = (Double.parseDouble(((List) map.get("OtherIncome_MM_金融服务费收入")).get(0).toString()));
            tMM.setFinancingServiceFeeMargin(b22);//金融服务费收入
            Double b23 = (Double.parseDouble(((List) map.get("OtherIncome_MM_上牌服务费收入")).get(0).toString()));
            tMM.setRegistrationServiceFeeMargin(b23);//上牌服务费收入
            Double b24 = (Double.parseDouble(((List) map.get("OtherIncome_MM_其他服务费收入")).get(0).toString()));
            tMM.setOtherServiceFeeMargin(b24);//其他服务费收入
            tMonthlySaleRptRepository.save(tMM);


            //新增或更新AMG的数据
            TMonthlySaleRptModel tAMG = tMonthlySaleRptRepository.findByPermitAndYearAndMonthAndBrand(permit, year, month, "AMG");
            if (tAMG == null) {
                tAMG = new TMonthlySaleRptModel();
                tAMG.setPermit(permit);
                tAMG.setStatMonth(month);
                tAMG.setStatYear(year);
                tAMG.setModel("AMG");//品牌
            }
            Double c1 = Double.parseDouble(((List) map.get("Volume_AMG_零售签署目标")).get(0).toString());
            tAMG.setSignedRetailTa(c1);//零售签署目标（台次）
            Double c2 = (Double.parseDouble(((List) map.get("Volume_AMG_实际零售NBI")).get(0).toString()));
            tAMG.setActualRetailNbi(c2);//实际零售NBI（台次）
            Double c3 = (Double.parseDouble(((List) map.get("Volume_AMG_ROS零售目标")).get(0).toString()));
            tAMG.setRosRetailTa(c3);//ROS零售目标（台次）
            Double c4 = (Double.parseDouble(((List) map.get("Volume_AMG_实际零售NBI")).get(0).toString()));
            tAMG.setActualRetailRos(c4);//实际零售ROS（台次）

            Double c5 = (Double.parseDouble(((List) map.get("ClosingStock_AMG_90天以下库存台数")).get(0).toString()));
            tAMG.setLt89DaysStock(c5);//90天以下库存台数
            Double c6 = (Double.parseDouble(((List) map.get("ClosingStock_AMG_90-149天库存台数")).get(0).toString()));
            tAMG.setDaysStock90149(c6);//90-149天库存台数
            Double c7 = (Double.parseDouble(((List) map.get("ClosingStock_AMG_大于150天库存台数")).get(0).toString()));
            tAMG.setGet150DaysStock(c7);//大于150天库存台数

            Double c8 = (Double.parseDouble(((List) map.get("Finance_AMG_新车外部销售收入")).get(0).toString()));
            tAMG.setNewCarExternalSalesRevenue(c8);//新车外部销售收入
            Double c9 = (Double.parseDouble(((List) map.get("Finance_AMG_GP1金额")).get(0).toString()));
            tAMG.setActualGpi(c9);//GP1
            Double c10 = (Double.parseDouble(((List) map.get("Finance_AMG_GP2金额")).get(0).toString()));
            tAMG.setActualGpii(c10);//GP2
            Double c11 = (Double.parseDouble(((List) map.get("Finance_AMG_SI金额")).get(0).toString()));
            tAMG.setActualSi(c11);//SI

            Double c12 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_二手车评估台数")).get(0).toString()));
            tAMG.setUsedCarAppraisalVolume(c12);//二手车评估台数
            Double c13 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_二手车置换台数")).get(0).toString()));
            tAMG.setUsedCarTradeInVolume(c13);//二手车置换台数
            Double c14 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_置换手续费收入")).get(0).toString()));
            tAMG.setTradeInCommission(c14);//置换手续费收入
            Double c15 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_后市场产品营业额")).get(0).toString()));
            tAMG.setAfterMarketProductRevenue(c15);//后市场产品营业额
            Double c16 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_后市场产品销售毛利")).get(0).toString()));
            tAMG.setAfterMarketProductGp(c16);//后市场产品销售毛利
            Double c17 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_新保台数")).get(0).toString()));
            tAMG.setNewCarInsurance(c17);//新保台数
            Double c18 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_新保手续费收入")).get(0).toString()));
            tAMG.setNewCarInsuranceCommission(c18);//新保手续费收入
            Double c19 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_金融零售数")).get(0).toString()));
            tAMG.setNewCarFinancing(c19);//金融零售数
            Double c20 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_新车Agility台数")).get(0).toString()));
            tAMG.setNewCarAgility(c20);//新车Agility台数
            Double c21 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_金融手续费收入")).get(0).toString()));
            tAMG.setFinancingCommission(c21);//金融手续费收入
            Double c22 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_金融服务费收入")).get(0).toString()));
            tAMG.setFinancingServiceFeeMargin(c22);//金融服务费收入
            Double c23 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_上牌服务费收入")).get(0).toString()));
            tAMG.setRegistrationServiceFeeMargin(c23);//上牌服务费收入
            Double c24 = (Double.parseDouble(((List) map.get("OtherIncome_AMG_其他服务费收入")).get(0).toString()));
            tAMG.setOtherServiceFeeMargin(c24);//其他服务费收入
            tMonthlySaleRptRepository.save(tAMG);

            //新增或更新SMART的数据
            TMonthlySaleRptModel tSmart = tMonthlySaleRptRepository.findByPermitAndYearAndMonthAndBrand(permit, year, month, "SMART");
            if (tSmart == null) {
                tSmart = new TMonthlySaleRptModel();
                tSmart.setPermit(permit);
                tSmart.setStatMonth(month);
                tSmart.setStatYear(year);
                tSmart.setModel("SMART");//品牌
            }
            Double d1 = Double.parseDouble(((List) map.get("Volume_Smart_零售签署目标")).get(0).toString());
            tSmart.setSignedRetailTa(d1);//零售签署目标（台次）
            Double d2 = (Double.parseDouble(((List) map.get("Volume_Smart_实际零售NBI")).get(0).toString()));
            tSmart.setActualRetailNbi(d2);//实际零售NBI（台次）
            Double d3 = (Double.parseDouble(((List) map.get("Volume_Smart_ROS零售目标")).get(0).toString()));
            tSmart.setRosRetailTa(d3);//ROS零售目标（台次）
            Double d4 = (Double.parseDouble(((List) map.get("Volume_Smart_实际零售NBI")).get(0).toString()));
            tSmart.setActualRetailRos(d4);//实际零售ROS（台次）

            Double d5 = (Double.parseDouble(((List) map.get("ClosingStock_Smart_90天以下库存台数")).get(0).toString()));
            tSmart.setLt89DaysStock(d5);//90天以下库存台数
            Double d6 = (Double.parseDouble(((List) map.get("ClosingStock_Smart_90-149天库存台数")).get(0).toString()));
            tSmart.setDaysStock90149(d6);//90-149天库存台数
            Double d7 = (Double.parseDouble(((List) map.get("ClosingStock_Smart_大于150天库存台数")).get(0).toString()));
            tSmart.setGet150DaysStock(d7);//大于150天库存台数

            Double d8 = (Double.parseDouble(((List) map.get("Finance_Smart_新车外部销售收入")).get(0).toString()));
            tSmart.setNewCarExternalSalesRevenue(d8);//新车外部销售收入
            Double d9 = (Double.parseDouble(((List) map.get("Finance_Smart_GP1金额")).get(0).toString()));
            tSmart.setActualGpi(d9);//GP1
            Double d10 = (Double.parseDouble(((List) map.get("Finance_Smart_GP2金额")).get(0).toString()));
            tSmart.setActualGpii(d10);//GP2
            Double d11 = (Double.parseDouble(((List) map.get("Finance_Smart_SI金额")).get(0).toString()));
            tSmart.setActualSi(d11);//SI

            Double d12 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_二手车评估台数")).get(0).toString()));
            tSmart.setUsedCarAppraisalVolume(d12);//二手车评估台数
            Double d13 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_二手车置换台数")).get(0).toString()));
            tSmart.setUsedCarTradeInVolume(d13);//二手车置换台数
            Double d14 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_置换手续费收入")).get(0).toString()));
            tSmart.setTradeInCommission(d14);//置换手续费收入
            Double d15 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_后市场产品营业额")).get(0).toString()));
            tSmart.setAfterMarketProductRevenue(d15);//后市场产品营业额
            Double d16 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_后市场产品销售毛利")).get(0).toString()));
            tSmart.setAfterMarketProductGp(d16);//后市场产品销售毛利
            Double d17 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_新保台数")).get(0).toString()));
            tSmart.setNewCarInsurance(d17);//新保台数
            Double d18 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_新保手续费收入")).get(0).toString()));
            tSmart.setNewCarInsuranceCommission(d18);//新保手续费收入
            Double d19 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_金融零售数")).get(0).toString()));
            tSmart.setNewCarFinancing(d19);//金融零售数
            Double d20 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_新车Agility台数")).get(0).toString()));
            tSmart.setNewCarAgility(d20);//新车Agility台数
            Double d21 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_金融手续费收入")).get(0).toString()));
            tSmart.setFinancingCommission(d21);//金融手续费收入
            Double d22 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_金融服务费收入")).get(0).toString()));
            tSmart.setFinancingServiceFeeMargin(d22);//金融服务费收入
            Double d23 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_上牌服务费收入")).get(0).toString()));
            tSmart.setRegistrationServiceFeeMargin(d23);//上牌服务费收入
            Double d24 = (Double.parseDouble(((List) map.get("OtherIncome_Smart_其他服务费收入")).get(0).toString()));
            tSmart.setOtherServiceFeeMargin(d24);//其他服务费收入

            Double e6 = (Double.parseDouble(((List) map.get("SalesProductivity_Smart_销售部人数")).get(0).toString()));
            tSmart.setSalesDeptHeadcount(e6);
            tMonthlySaleRptRepository.save(tSmart);


            //新增或更新财务费用的数据
            TMonthlySaleRptModel ex = tMonthlySaleRptRepository.findByPermitAndYearAndMonthAndBrand(permit, year, month, "EXPENSES");
            if (ex == null) {
                ex = new TMonthlySaleRptModel();
                ex.setPermit(permit);
                ex.setStatMonth(month);
                ex.setStatYear(year);
                ex.setModel("EXPENSES");//品牌Expenses
            }
            // 销售直接费用预算
            Double e1 = (Double.parseDouble(((Integer[]) map.get("Finance_Expenses_销售直接费用预算"))[Integer.valueOf(month) - 1].toString()));
            ex.setBudgetSalesDirectExpenses(e1);
            Double e2 = (Double.parseDouble(((Integer[]) map.get("Finance_Expenses_实际销售直接费用"))[Integer.valueOf(month) - 1].toString()));
            ex.setActualSalesDirectExpenses(e2);
            Double e3 = (Double.parseDouble(((Integer[]) map.get("Finance_Expenses_销售间接费用预算"))[Integer.valueOf(month) - 1].toString()));
            ex.setBudgetSalesIndirectExpenses(e3);
            Double e4 = (Double.parseDouble(((Integer[]) map.get("Finance_Expenses_实际销售间接费用"))[Integer.valueOf(month) - 1].toString()));
            ex.setActualSalesIndirectExpenses(e4);
            tMonthlySaleRptRepository.save(ex);

            //新增或更新smart销售部人数
            TMonthlySaleRptModel ex1 = tMonthlySaleRptRepository.findByPermitAndYearAndMonthAndBrand(permit, year, month, "MBMMAMG");
            if (ex1 == null) {
                ex1 = new TMonthlySaleRptModel();
                ex1.setPermit(permit);
                ex1.setStatMonth(month);
                ex1.setStatYear(year);
                ex1.setModel("MBMMAMG");//品牌
            }
            Double e5 = (Double.parseDouble(((List) map.get("SalesProductivity_MB+MM+AMG_销售部人数")).get(0).toString()));
            ex1.setSalesDeptHeadcount(e5);
            tMonthlySaleRptRepository.save(ex1);

        }
    }

    private String getFormatDate(Date dt) {
        return new SimpleDateFormat("yyyy年MM月dd日").format(dt);
    }

    private String getFormatUtilDate(java.util.Date dt) {
        return new SimpleDateFormat("yyyy年MM月dd日").format(dt);
    }

    public void setWeelySmRosReport(String dateone) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new java.util.Date());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");


        try {
            if (dateone != null) {
                calendar.setTime(sdf1.parse(dateone));
            }
        } catch (Exception e) {
            logger.error("时间转换失败", e);
        }

        //calendar.add(Calendar.DAY_OF_MONTH, -1);
        java.util.Date date = calendar.getTime();
        String yDate = sdf1.format(date);

        String update = sdf2.format(date);

        calendar.add(Calendar.YEAR, -1);
        java.util.Date date2 = calendar.getTime();
        String yDate2 = sdf1.format(date2);


        calendar.add(Calendar.YEAR, -1);
        java.util.Date date3 = calendar.getTime();
        String yDate3 = sdf1.format(date3);


        //获取许可
        List<String> permits = lsh经销商表Repository.findPermit();
        //获取各种报表数据
        tWeeklySm2RosRptRepository.deleteByDate(update);
        //tWeeklySm2RosRptRepository.deleteAllInBatch();

        for (String permit : permits) {
           /* 区域集团报表对应月份生产但尚未被采购的资源*/
            //作为主Map  进行操作
            //  permit="ENTL20";
            Map<String, TWeeklySm2RosRptModel> resultAll = Maps.newHashMap();
            /*2016*/
            List noSaleCars = weekReprotRepository.getNoSaleCars(permit, yDate);
            for (Object resulta : noSaleCars) {
                TWeeklySm2RosRptModel model = new TWeeklySm2RosRptModel();
                Map results = (Map) resulta;
                results.put("许可", permit);
                model.setPermit(permit);
                if (results.get("分类") != null) {
                    model.setSegment(results.get("分类").toString());
                }
                if (results.get("车型_DE") != null) {
                    model.setModelDe(results.get("车型_DE").toString());
                }
                if (results.get("底盘") != null) {
                    model.setClassis(results.get("底盘").toString());
                }
                if (results.get("车型") != null) {
                    model.setModel(results.get("车型").toString());
                }
                if (results.get("months") != null) {
                    model.setAllocationYear3(results.get("months").toString());
                }

                String uniqueCode = results.get("uniqueCode").toString();
                resultAll.put(uniqueCode, model);
            }
            /*2015*/
            List noSaleCars2 = weekReprotRepository.getNoSaleCars(permit, yDate2);
            for (Object resultb : noSaleCars2) {
                Map results = (Map) resultb;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("months") != null) {
                    model.setAllocationYear2(results.get("months").toString());
                }
            }
            /*2014*/
            List noSaleCars3 = weekReprotRepository.getNoSaleCars(permit, yDate3);
            for (Object result : noSaleCars3) {
                Map results = (Map) result;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("months") != null) {
                    model.setAllocationYear1(results.get("months").toString());
                }
            }
            /** 获取零售数*/
            List salesCars = weekReprotRepository.getSalesCars(permit, yDate);
            for (Object resultc : salesCars) {
                Map results = (Map) resultc;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("RETAIL_SALE_WEEKLY") != null) {
                    model.setRetailSaleWeekly(Integer.parseInt(results.get("RETAIL_SALE_WEEKLY").toString()));
                }
                if (results.get("RETAIL_SALE_MTD") != null) {
                    model.setRetailSaleMtd(Integer.parseInt(results.get("RETAIL_SALE_MTD").toString()));
                }
                if (results.get("RETAIL_SALE_YTD") != null) {
                    model.setRetailSaleYtd(Integer.parseInt(results.get("RETAIL_SALE_YTD").toString()));
                }

            }
            /**  获取订单数  */
            List orderCars = weekReprotRepository.getOrderCars(permit, yDate);
            for (Object resultd : orderCars) {
                Map results = (Map) resultd;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("weekly_customer_order") != null) {
                    model.setCustomerOrderWeekly(Integer.parseInt(results.get("weekly_customer_order").toString()));
                }
                if (results.get("monthyly_customer_order") != null) {
                    model.setCustomerOrderMtd(Integer.parseInt(results.get("monthyly_customer_order").toString()));
                }
                if (results.get("yearly_customer_order") != null) {
                    model.setCustomerOrderYtd(Integer.parseInt(results.get("yearly_customer_order").toString()));
                }


            }
              /*未开票订单*/
            List noInvOrders = weekReprotRepository.getNoInvOrders(permit);
            for (Object resulte : noInvOrders) {
                Map results = (Map) resulte;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("CUSTOMER_ORDER_TOTAL_UNFULFILLED") != null) {
                    model.setCustomerOrderTotalUnfulfilled(Integer.parseInt(results.get("CUSTOMER_ORDER_TOTAL_UNFULFILLED").toString()));
                }
            }
            /*有单库存*/
            List stockWithOrder = weekReprotRepository.getStockWithOrder(permit);
            for (Object resultf : stockWithOrder) {
                Map results = (Map) resultf;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("STOCK_WITH_ORDER") != null) {
                    model.setStockWithOrder(Integer.parseInt(results.get("STOCK_WITH_ORDER").toString()));
                }


            }
              /*无单库存*/
            List stockWithOutOrder = weekReprotRepository.getStockWithOutOrder(permit);
            for (Object resultg : stockWithOutOrder) {
                Map results = (Map) resultg;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("STOCK_WITHOUT_ORDER") != null) {
                    model.setStockWithoutOrder(Integer.parseInt(results.get("STOCK_WITHOUT_ORDER").toString()));
                }

            }
               /*交车但尚未开票的车*/
            List noInvStock = weekReprotRepository.getNoInvStock(permit);
            for (Object resulth : noInvStock) {
                Map results = (Map) resulth;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("STOCK_PENDING_FOR_INVOICE") != null) {
                    model.setStockPendingForInvoice(Integer.parseInt(results.get("STOCK_PENDING_FOR_INVOICE").toString()));
                }
            }

                 /*开票但尚未交车*/
            List invoiceNoGive = weekReprotRepository.getInvoiceNoGive(permit);
            for (Object resulth : invoiceNoGive) {
                Map results = (Map) resulth;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("RETAIL_SALE_WITHOUT_GIVECAR") != null) {
                    model.setRetailSaleWithoutGivecar(Integer.parseInt(results.get("RETAIL_SALE_WITHOUT_GIVECAR").toString()));

                }
            }

            /* 截止统计日，有批发日期且无入库日车的车辆台数*/
            List wholesaleNotIntoStorage = weekReprotRepository.getWholesaleNotIntoStorage(permit);
            for (Object resulth : wholesaleNotIntoStorage) {
                Map results = (Map) resulth;
                String uniqueCode = results.get("uniqueCode").toString();
                TWeeklySm2RosRptModel model = resultAll.get(uniqueCode);
                if (results.get("WHOLESALE_NOTINTO_STORAGE") != null) {
                    model.setWholesaleNotintoStorage(Integer.parseInt(results.get("WHOLESALE_NOTINTO_STORAGE").toString()));
                }
            }

            /*保存*/
            Collection con = resultAll.values();
            Iterator ite = con.iterator();
            ArrayList<TWeeklySm2RosRptModel> lisResul = new ArrayList<TWeeklySm2RosRptModel>();
            while (ite.hasNext()) {
                TWeeklySm2RosRptModel tWeeklySm2RosRptModel = (TWeeklySm2RosRptModel) ite.next();
                 if (tWeeklySm2RosRptModel.getInsertType()) {
                    tWeeklySm2RosRptModel.setUpdateDate(update);
                    lisResul.add(tWeeklySm2RosRptModel);
                 }
            }
            tWeeklySm2RosRptRepository.save(lisResul);
        }
    }

    @Override
    public void setActualFinanceServeFree() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01");
            String date = sdf.format(new java.util.Date());
            List list = timedTaskRepository.getActualFinanceServeFree();
            if (list != null && !list.isEmpty()) {
                for (Object o : list) {
                    Map map = (Map) o;
                    Lsh金融服务费ModelPK lsh金融服务费ModelPK = new Lsh金融服务费ModelPK();
                    lsh金融服务费ModelPK.set许可(String.valueOf(map.get("permit")));
                    lsh金融服务费ModelPK.set日期(new Date(sdf.parse(date).getTime()));
                    Lsh金融服务费Model lsh金融服务费Model = lsh金融服务费Repository.findOne(lsh金融服务费ModelPK);
                    if (lsh金融服务费Model != null) {
                        lsh金融服务费Model.set经销商实际值(String.valueOf(map.get("actualVale")));
                        lsh金融服务费Model.set更新账号("Admin");
                        lsh金融服务费Model.set更新时间(new Timestamp(new java.util.Date().getTime()));
                        lsh金融服务费Repository.save(lsh金融服务费Model);
                    } /*else {
                        lsh金融服务费Model = new Lsh金融服务费Model();
                        lsh金融服务费Model.set许可(String.valueOf(map.get("permit")));
                        lsh金融服务费Model.set日期((new Date(sdf.parse(date).getTime())));
                        lsh金融服务费Model.set经销商实际值(String.valueOf(map.get("actualVale")));
                    }*/

                }
            }
        } catch (Exception e) {
            logger.error("获取经销商服务费实际值异常", e);
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Override
    public void setFlowupReport(String dateone)  throws Exception {

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new java.util.Date());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
        java.util.Date date = calendar.getTime();
        try {
            if (dateone != null) {
                calendar.setTime(sdf1.parse(dateone));
            }
        } catch (Exception e) {
            logger.error("时间转换失败", e);
        }
        String update = sdf1.format(date);
        java.util.Date flowDate=sdf1.parse(dateone);
        flowupReportRepository.deleteByDate(flowDate);

         List<Map<String, Object>>  noSaleCars = reportRepository.getCurrentCluesList(null,dateone);
        List<TFlowupReportModel> result =new ArrayList();
        for (Map a:noSaleCars){
            TFlowupReportModel model=new TFlowupReportModel();
            if (a.get("许可") != null&&!"".equals(a.get("许可"))&&!" ".equals(a.get("许可")) ) {
                model.setPermit(a.get("许可").toString());
            }
            model.setFollowUpdate(flowDate);
            if (a.get("线索姓名") != null&&!"".equals(a.get("线索姓名"))&&!" ".equals(a.get("线索姓名"))) {
                model.setCusName(a.get("线索姓名").toString());
            }
            if (a.get("电话号码") != null&&!"".equals(a.get("电话号码") ) &&!" ".equals(a.get("电话号码") )) {
                model.setTel(a.get("电话号码") .toString());
            }
            if (a.get("线索创建日期") != null&&!"".equals(a.get("线索创建日期"))&&!" ".equals(a.get("线索创建日期"))) {
                java.util.Date da=DateFormatUtils.getFormatDate(a.get("线索创建日期").toString(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD);
                model.setCreatedDate(da);
            }
            if (a.get("来源渠道") != null&&!"".equals(a.get("来源渠道"))&&!" ".equals(a.get("来源渠道"))) {
                model.setSource(a.get("来源渠道").toString() );
            }
            if (a.get("意向级别") != null&&!"".equals(a.get("意向级别")) &&!" ".equals(a.get("意向级别"))) {
                model.setCusLevel(a.get("意向级别").toString());
            }
            if (a.get("意向车型") != null&&!"".equals(a.get("意向车型"))&&!" ".equals(a.get("意向车型"))  ) {
                model.setCarType(a.get("意向车型").toString());
            }
            if (a.get("销售顾问ID") != null&&!"".equals(a.get("销售顾问ID"))&&!" ".equals(a.get("销售顾问ID"))) {
                model.setScId(a.get("销售顾问ID").toString() );
            }
            if (a.get("销售顾问") != null&&!"".equals(a.get("销售顾问"))&&!" ".equals(a.get("销售顾问"))) {
                model.setScName(a.get("销售顾问").toString());
            }
            if (a.get("销售组") != null&&!"".equals(a.get("销售组"))&&!" ".equals(a.get("销售组"))) {
                model.setScGroup(a.get("销售组").toString());
            }
            if (a.get("当天跟进通话时长") != null&&!"".equals(a.get("当天跟进通话时长")) &&!" ".equals(a.get("当天跟进通话时长"))) {
                model.setNowDuration(Integer.parseInt(a.get("当天跟进通话时长").toString() ));
            }
            if (a.get("当天跟进备注") !=null &&!"".equals(a.get("当天跟进备注")) &&!" ".equals(a.get("当天跟进备注"))) {
                model.setNowRemark(a.get("当天跟进备注").toString());
            }
            if (a.get("上一次跟进日期") != null&&!"".equals(a.get("上一次跟进日期"))&&!" ".equals(a.get("上一次跟进日期"))) {
                java.util.Date da=DateFormatUtils.getFormatDate(a.get("上一次跟进日期").toString(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD);
                model.setOldDate(da);
            }
            if (a.get("上一次跟进通话时长") != null&&!"".equals(a.get("上一次跟进通话时长")) &&!" ".equals(a.get("上一次跟进通话时长"))) {
                model.setOldDuration(Integer.parseInt(a.get("上一次跟进通话时长").toString() ));
            }
            if (a.get("上一次跟进备注") != null&&!"".equals(a.get("上一次跟进备注"))&&!" ".equals(a.get("上一次跟进备注")) ) {
                model.setOldRemark(a.get("上一次跟进备注").toString());
            }
            if (a.get("最近一次进店日期") != null&&!"".equals(a.get("最近一次进店日期")) &&!" ".equals(a.get("最近一次进店日期"))) {
                java.util.Date da=DateFormatUtils.getFormatDate(a.get("最近一次进店日期").toString(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD);
                model.setOldInDate(da);
            }
            if (a.get("订单日期") != null&&!"".equals(a.get("订单日期")) &&!" ".equals(a.get("订单日期"))) {
                java.util.Date da=DateFormatUtils.getFormatDate(a.get("订单日期").toString(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD);
                model.setOrderDate(da);
            }
            if (a.get("开票日期") != null&&!"".equals(a.get("开票日期"))&&!" ".equals(a.get("开票日期"))) {
                java.util.Date da= DateFormatUtils.getFormatDate(a.get("开票日期").toString(),DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD);
                model.setInvoiceDate(da);
            }

           model.setUpdateTime(new Timestamp( new java.util.Date().getTime()));
            result.add(model);
        }
        flowupReportRepository.save(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void everyMonthCheckOfClue () throws Exception {
        logger.info("月度盘点线索信息--战败信息记录到战败日志表");
        timedTaskRepository.insertTDefeatLog();
        logger.info("月度盘点线索信息--修改顾客状态及休眠日期、战败日期");
        int num = timedTaskRepository.updateClueStateAndDate();
        if (num <= 0) {
            logger.info("月度盘点线索信息--本次盘点未修改顾客信息，请确认");
        }
        logger.info("月度盘点线索信息--统计活跃休眠顾客信息");
        List list = timedTaskRepository.findClueCountInfo();
        List<线索统计Model> models = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Object o : list) {
                Map map = (Map) o;
                线索统计Model model = new 线索统计Model();
                if (StringUtils.isNullOrBlank(map.get("许可")) || StringUtils.isNullOrBlank(map.get("车型编号"))
                        || StringUtils.isNullOrBlank(map.get("渠道")) || StringUtils.isNullOrBlank(map.get("销售顾问"))
                        || StringUtils.isNullOrBlank(map.get("周期")) || StringUtils.isNullOrBlank(map.get("有效线索数"))) {
                    continue;
                }
                model.set许可(map.get("许可").toString());
                model.set车型编号(Integer.parseInt(map.get("车型编号").toString()));
                model.set渠道(map.get("渠道").toString());
                model.set销售顾问(map.get("销售顾问").toString());
                model.set周期(map.get("周期").toString());
                model.set有效线索数(Integer.parseInt(map.get("有效线索数").toString()));
                models.add(model);
            }
            线索统计Repository.save(models);
        }
    }
}
